package com.wlt.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.wlt.ZfbPayConfig;
import com.wlt.mapper.PaymentMapper;
import com.wlt.pojo.Orders;
import com.wlt.pojo.Payment;
import com.wlt.result.BusException;
import com.wlt.result.CodeEnum;
import com.wlt.utils.ZfbVerifierUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@DubboService
public class ZfbPayServiceImpl implements ZfbPayService {
    @Autowired
    private ZfbPayConfig zfbPayConfig;
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private PaymentMapper paymentMapper;
    
    @Override
    public String pcPay (Orders orders) {
        // 判断订单状态，只有未支付的订单才会生成订单二维码
        if (orders.getStatus() != 1) {
            throw new BusException(CodeEnum.ORDER_STATUS_ERROR);
        }
        
        // 创建请求对象
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        
        // 设置请求内容
        // 设置回调接口
        request.setNotifyUrl(zfbPayConfig.getNotifyUrl() + zfbPayConfig.getPcNotify());
        // 将订单内容变JSON字符串
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orders.getId());         // 订单编号
        bizContent.put("total_amount", orders.getPayment());    // 订单金额
        bizContent.put("subject", orders.getCartGoods().get(0).getGoodsName()); // 订单标题
        
        request.setBizContent(bizContent.toJSONString());
        
        
        try {
            // 发送请求
            AlipayTradePrecreateResponse execute = alipayClient.execute(request);
            
            // 返回二维码
            return execute.getQrCode();
        }
        catch (AlipayApiException e) {
            throw new BusException(CodeEnum.QR_CODE_ERROR);
        }
    }
    
    @Override
    public void checkSign (Map<String, Object> paramMap) {
        // 获取所有参数
        Map<String, String[]> requestParameterMap = (Map<String, String[]>) paramMap.get("requestParameterMap");
        
        // 验签
        boolean valid = ZfbVerifierUtils.isValid(requestParameterMap, zfbPayConfig.getPublicKey());
        
        // 验签失败抛异常
        if (!valid) {
            throw new BusException(CodeEnum.CHECK_SIGN_ERROR);
        }
    }
    
    @Override
    public void addPayment (Payment payment) {
        paymentMapper.insert(payment);
    }
}
